<template>
  <div class="all">
    <table class="search-box">
      <tr class="vat">
        <td class="search">
          <el-button type="primary" @click="showAddDialog"> 新增 </el-button>
          <el-input
            placeholder="编号/书名/作者/出版社"
            clearable
            class="keyword ml10"
            v-model="searchKeyword"
            @input="inputSearch"
          >
            <template #prepend>关键字</template>
          </el-input>
          <!-- <el-button type="primary" class="ml10" @click="search">
            搜索
          </el-button> -->
          <!-- <el-button @click="clearSearch">清空</el-button> -->
          <el-button type="primary" @click="reload"> 刷新 </el-button>
        </td>
        <!-- <td class="tar">
        </td> -->
      </tr>
    </table>
    <div class="indexBody">
      <div class="demo-pagination-block">
        <div class="demonstration">
          <el-table v-loading="loading" :data="paginatedItems" style="width: 100%">
            <el-table-column label="编号" prop="id" width="80px" />
            <el-table-column label="图片">
              <template #default="scope">
                <img
                  :src="scope.row.image"
                  style="width: 100px; height: auto"
                  alt="书籍图片"
                />
              </template>
            </el-table-column>
            <el-table-column label="书名" prop="title" />
            <el-table-column label="作者" prop="author" />
            <el-table-column label="出版社" prop="press" />
            <el-table-column label="简介" prop="about" width="500px" />
            <el-table-column label="价格" width="80px">
              <template #default="scope">
                {{ scope.row.price }}元
              </template>
            </el-table-column>
            <el-table-column align="right">
              <template #default="scope">
                <el-button size="small" @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  @click="showDeleteDialog(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[15, 30, 60, 120, 240]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="addDialogVisible"
      @opened="resetFormData"
      title="新增信息"
      width="40rem"
    >
      <el-form :model="addFormData">
        <el-form-item label="图片" label-width="auto">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            name="image"
            action="http://localhost:3000/api/books/upload/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="书名" label-width="auto">
          <el-input v-model="addFormData.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者" label-width="auto">
          <el-input v-model="addFormData.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版社" label-width="auto">
          <el-input v-model="addFormData.press" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" label-width="auto">
          <el-input
            v-model="addFormData.about"
            type="textarea"
            autocomplete="off"
            placeholder="请输入书籍描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="auto">
          <el-input v-model="addFormData.price" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelAdd">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="editDialogVisible" title="编辑信息" width="40rem">
      <el-form :model="editFormData">
        <el-form-item label="图片" label-width="auto">
          <el-upload
            class="upload-demo"
            name="image"
            action="http://localhost:3000/api/books/upload/"
            :on-success="handleEditUploadSuccess"
            :show-file-list="false"
            list-type="picture"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
          <img
            v-if="editFormData.image"
            :src="editFormData.image"
            style="
              width: 100px;
              height: auto;
              margin-top: 10px;
              margin-left: 20px;
            "
            alt="书籍图片"
          />
        </el-form-item>
        <el-form-item label="书名" label-width="auto">
          <el-input v-model="editFormData.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者" label-width="auto">
          <el-input v-model="editFormData.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版社" label-width="auto">
          <el-input v-model="editFormData.press" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" label-width="auto">
          <el-input
            v-model="editFormData.about"
            type="textarea"
            autocomplete="off"
            placeholder="请输入书籍描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="auto">
          <el-input
            v-model="editFormData.price"
            autocomplete="off"
            placeholder="请输入价格"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <!-- <el-button @click="editDialogVisible = false">取消</el-button> -->
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
      <p>确认要删除这条数据吗？</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import _ from "lodash";

const items = ref([]);
const searchKeyword = ref("");
const deleteDialogVisible = ref(false);
const deleteItem = ref(null); // 用于存储要删除的项
const totalItems = ref(0); // 用于存储总条数的响应式变量
const currentPage = ref(1);
const pageSize = ref(15);
const small = ref(true);
const background = ref(true);
const disabled = ref(false);
const fileList = ref([]);
const editDialogVisible = ref(false);
// const editItemId = ref(null);
// const editableAccount = ref("");
// const editablePassword = ref("");
const loading = ref(false);

const handleRemove = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
};
const handlePreview = (file) => {
  // console.log(file)
};
const handleSuccess = (response, file, fileList) => {
  // console.log('File uploaded successfully:', response.imageUrl);
  // 这里可以处理服务器返回的数据，比如将图片URL保存到数据中
  addFormData.value.image = response.imageUrl;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  // fetchData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  // fetchData();
};
const paginatedItems = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return items.value.slice(start, end);
});

onMounted(() => {
  fetchData();
  authHeaders();
  // console.log(localStorage.Authorization);
});

const editItem = (item) => {
  editItemId.value = item.id;
  editableAccount.value = item.account;
  editablePassword.value = item.password;
};

const editFormData = ref({
  image: "",
  title: "",
  author: "",
  press: "",
  about: "",
  price: "",
});

function showEditDialog(item) {
  editItem.value = item;
  editFormData.value = {
    image: item.image,
    title: item.title,
    author: item.author,
    press: item.press,
    about: item.about,
    price: item.price,
  };
  editDialogVisible.value = true;
}

function cancelAdd() {
  if (addFormData.value.image!=null) {
    axios.delete(`http://localhost:3000/api/books/deleteimage`, {
      data: {
        imageUrl: addFormData.value.image,
      },
    }).catch((error) => {
      ElMessage.error("删除未保存图片失败" + error.response.data.message);
    });
  }  
  addDialogVisible.value = false; // 关闭对话框
}

function cancelEdit() {
  if (editFormData.value.image!=editItem.value.image) {
    axios.delete(`http://localhost:3000/api/books/deleteimage`, {
      data: {
        imageUrl: editFormData.value.image,
      },
    }).catch((error) => {
      ElMessage.error("删除未保存图片失败" + error.response.data.message);
    });
  }  
  editDialogVisible.value = false; // 关闭对话框
}



//修改图书信息
async function submitEditForm() {
  try {
    if (editFormData.value.image != editItem.value.image) {
      await axios.delete(`http://localhost:3000/api/books/deleteimage`, {
        data: {
          imageUrl: editItem.value.image,
        },
      });
    }
    const response = await axios.put(
      `http://localhost:3000/api/books/items/${editItem.value.id}`,
      editFormData.value
    );
    if (response.data.message === "修改成功") {
      ElMessage.success("修改成功");
      editDialogVisible.value = false;
      // 重新获取数据
      fetchData();
    } else {
      ElMessage.error("修改失败");
    }
  } catch (error) {
    ElMessage.error(error.response.data.message);
  }
}
function handleEditUploadSuccess(response) {
  if (response && response.imageUrl) {
    editFormData.value.image = response.imageUrl;
    ElMessage.success("图片上传成功");
  } else {
    ElMessage.error("图片上传失败，无法获取图片链接");
  }
}



async function authHeaders() {
  const token = localStorage.Authorization;
  return token;
}

//获取账号数据
async function fetchData() {
  loading.value = true;
  try {
    const response = await axios.get("http://localhost:3000/api/books/info");
    // 添加500ms延时
    await new Promise(resolve => setTimeout(resolve, 400));
    items.value = response.data;
    totalItems.value = response.data.length;
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    }
  } finally {
    loading.value = false;
  }
}

// 使用防抖处理实时搜索
const inputSearch = _.debounce(() => {
  if (searchKeyword.value.trim() !== "") {
    search();
  } else {
    fetchData();
  }
}, 300); // 300ms的延迟

async function search() {
  try {
    const response = await axios.get("http://localhost:3000/api/books/search", {
      params: { keyword: searchKeyword.value },
    });
    items.value = response.data;
    totalItems.value = response.data.length;
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    }
  }
}

function clearSearch() {
  searchKeyword.value = "";
}

function reload() {
  location.reload();
}

const addDialogVisible = ref(false);
const addFormData = ref({
  image: "",
  title: "",
  author: "",
  press: "",
  about: "",
  price: "",
});

//清空窗口内容
const resetFormData = () => {
  addFormData.value = {
    image: "",
    title: "",
    author: "",
    press: "",
    about: "",
    price: "",
  };
  fileList.value = [];
};

function showAddDialog() {
  addDialogVisible.value = true;
}

//新增账号数据
async function submitAddForm() {
  try {
    if (!addFormData.value.title.trim() || 
        !addFormData.value.author.trim() || 
        !addFormData.value.press.trim() || 
        !addFormData.value.about.trim() || 
        !addFormData.value.price.trim()) {
      ElMessage.error("所有字段都必须填写");
      return;
    }
    const response = await axios.post(
      "http://localhost:3000/api/books/add",
      addFormData.value
    );
    if (response.data.message === "添加成功") {
      ElMessage.success(response.data.message);
      addDialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error("添加失败");
    }
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    }
  }
}

function showDeleteDialog(item) {
  // 假设 deleteItem 是用于存储要删除的项的响应式变量
  deleteItem.value = item;
  deleteDialogVisible.value = true;
}

// 删除账号信息
async function confirmDelete() {
  if (deleteItem.value) {
    try {
      const response = await axios.delete(
        `http://localhost:3000/api/books/delete/${deleteItem.value.id}`
      );
      if (response.data.message === "删除成功") {
        ElMessage.success(response.data.message);
        fetchData();
        deleteDialogVisible.value = false;
      } else {
        ElMessage.error("删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败，请稍后再试");
    }
  }
}

const getTotalItems = async () => {
  try {
    const response = await axios.get("http://localhost:3000/api/books/total");
    totalItems.value = response.data.total;
  } catch (error) {
    //console.error("获取数据总条数失败:", error);
  }
};

// 调用 getTotalItems 方法以获取数据的总数
getTotalItems();

// 使用 defineExpose 显式地暴露给模板的属性和方法
defineExpose({
  items,
  searchKeyword,
  fetchData,
  search,
  clearSearch,
  reload,
});
</script>
<style scoped>
.all{
  margin-bottom: 80px;
}

.search-box {
  margin: 12px 4px 30px 0px;
  width: 40%;
}

.search {
  display: flex;
  padding: 0;
}

.search .el-button {
  margin-right: 10px;
  /* 添加按钮之间的间隔 */
}

.search .ml10 {
  /* margin-left: 10px; */
  /* 添加额外的左侧间距 */
}

.search .el-input {
  margin-right: 10px;
  /* 添加输入框与后面按钮之间的间隔 */
}

/* 确保最后一个按钮后面没有多余的间隔 */
.search .el-button:last-child {
  margin-right: 0;
}

.tar {
  margin: 0px 0px 0px 0px;
}

.tar .el-button {
  margin-left: 10px;
}

.el-pagination {
  position: absolute;
  z-index: 100;
  bottom: 2rem;
  left: 47rem;
  background-color: whitesmoke;
  padding: 10px;
  border-radius: 25px;
}

.demonstration {
  height: 90%;
}

.el-table {
  height: 97%;
}

.el-table-column {
  height: 10rem;
}
</style>